<template>
  <div class="activity-form">
    <el-form :model="form" label-width="150px" label-position="left">
      <el-form-item label="活动名称：" required>
        <el-input
          v-model="form.activityName"
          placeholder="请输入活动名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="活动时间：" required>
        <el-date-picker
          v-model="form.activityTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="参与用户：" required>
        <el-radio-group v-model="form.joinUser" @change="handleUserTypeChange">
          <el-radio
            v-for="item in userTypeList"
            :lable="item.dictName"
            :value="item.dictCode"
            >{{ item.dictName }}</el-radio
          >
        </el-radio-group>

        <div v-if="form.joinUser === 2" class="user-conditions">
          <el-form-item label="请选择用户等级：" label-width="170px">
            <el-select v-model="form.userGarde" placeholder="请选择" clearable>
              <el-option
                v-for="item in userLevelList"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="请选择是否是付费会员：" label-width="170px">
            <el-select v-model="form.userIsVip" placeholder="请选择" clearable>
              <el-option
                v-for="item in isVipList"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="请选择用户分组：" label-width="170px">
            <el-select placeholder="请选择" clearable multiple>
              <el-option
                v-for="group in userGroups"
                :label="group.label"
                :value="group.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="请选择用户标签：" label-width="170px">
            <el-select placeholder="请选择">
              <el-option
                v-for="tag in userTags"
                :key="tag.value"
                :label="tag.value"
              >
                {{ tag.label }}
              </el-option>
            </el-select>
          </el-form-item>

          <div class="condition-hint">
            若四个条件都设置后必须这些条件能满足的用户才能参加抽奖
          </div>
        </div>
      </el-form-item>

      <el-form-item label="单次抽奖消耗积分：" required>
        <el-input-number
          v-model="form.expendScore"
          :min="0"
          placeholder="请输入消耗积分"
        />
      </el-form-item>
      <!-- 奖品规则部分 -->
      <div class="section-title">奖品规则设置</div>
      <el-table
        :data="prizeRules"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ruleId" label="序号" width="60" align="center" />
        <el-table-column label="图片" width="100" align="center">
          <template #default="scope">
            <img :src="scope.row.ruleCover" width="50" height="50" />
          </template>
        </el-table-column>
        <el-table-column prop="ruleName" label="名称" width="120" />
        <el-table-column prop="rulePrize" label="奖品" width="150" />
        <el-table-column label="中奖抽签图片" width="120" align="center">
          <template #default="scope">
            <img :src="scope.row.ruleImage" width="50" height="50" />
          </template>
        </el-table-column>
        <el-table-column
          prop="prizeNumber"
          label="数量"
          width="80"
          align="center"
        >
          <template #default="scope">
            <el-input
              v-model.number="scope.row.prizeNumber"
              autocomplete="off"
              type="number"
              min="0"
              @change="prizeNumberChange(scope.row.prizeNumber)"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="prizeProbability"
          label="奖品概率"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-input
              v-model.number="scope.row.prizeProbability"
              autocomplete="off"
              type="number"
              min="0"
              @change="prizeProbabilityChange(scope.row.prizeProbability)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="text" @click="editPrize(scope.$index, scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 活动背景设置 -->
      <div class="section-title">活动背景设置</div>
      <el-form-item label="活动背景图：">
        <el-upload
          action="/api/activity/upload"
          list-type="picture-card"
          :on-success="uploadBackgroundImg"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <div class="upload-hint">建议尺寸（750*580）</div>
      </el-form-item>
      <el-form-item label="中奖名单：">
        <el-switch v-model="form.winner" />
      </el-form-item>
      <el-form-item label="中奖记录：">
        <el-switch v-model="form.winnerRecord" />
      </el-form-item>
      <el-form-item label="活动规则：">
        <el-switch v-model="form.activityRules" />
      </el-form-item>
      <el-form-item label="备注：" style="width: auto">
        <QuillEditor
          :options="editorOptions"
          ref="quillEditorRef"
          style="min-width: 730px"
          @blur="quillEditorBlur"
        />
      </el-form-item>
    </el-form>

    <div style="padding-top: 10%">
      <el-button type="primary" @click="addPrize">添加奖品</el-button>
    </div>
  </div>

  <!-- 奖品编辑对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="编辑奖品"
    width="50%"
    :close-on-click-modal="false"
  >
    <el-form :model="currentPrize" label-width="130px">
      <el-form-item label="奖品名称：">
        <el-input v-model="currentPrize.ruleName" />
      </el-form-item>
      <el-form-item label="奖品描述：">
        <el-input v-model="currentPrize.rulePrize" />
      </el-form-item>
      <el-form-item label="奖品数量：">
        <el-input-number v-model="currentPrize.prizeNumber" :min="0" />
      </el-form-item>
      <el-form-item label="奖品概率：">
        <el-input-number v-model="currentPrize.prizeProbability" :min="0" />
      </el-form-item>
      <el-form-item label="图片：">
        <img
          v-if="currentPrize.ruleCover && !noUploadImg"
          :src="currentPrize.ruleCover"
          width="150"
          height="150"
        />
        <el-upload
          ref="uploadCoverRef"
          action="/api/activity/upload"
          list-type="picture-card"
          :on-success="uploadImg"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="中奖抽签图片：">
        <img
          v-if="currentPrize.ruleImage && !noUploadLotteryImg"
          :src="currentPrize.ruleImage"
          width="150"
          height="150"
        />
        <el-upload
          ref="uploadImageRef"
          action="/api/activity/upload"
          list-type="picture-card"
          :on-success="uploadLotteryImg"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="savePrize">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { cloneDeep } from "lodash-es";
import { useRouter } from "vue-router";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";

const editorOptions = ref({
  modules: {
    toolbar: [
      ["bold", "italic", "underline", "strike"],
      ["blockquote", "code-block"],
      [{ header: 1 }, { header: 2 }],
      [{ list: "ordered" }, { list: "bullet" }],
      [{ script: "sub" }, { script: "super" }],
      [{ indent: "-1" }, { indent: "+1" }],
      [{ direction: "rtl" }],
      [{ size: ["small", false, "large", "huge"] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }],
      [{ font: [] }],
      [{ align: [] }],
      ["clean"],
    ],
  },
  placeholder: "请输入内容",
  theme: "snow",
});
const editorContent = ref("");
const quillEditorRef = ref(null);

const router = useRouter();

const form = ref({
  activityName: "",
  activityTime: [],
  joinUser: 1,
  userGarde: null,
  userIsVip: null,
  expendScore: 0,
  winner: true,
  winnerRecord: true,
  activityRules: true,
  ruleIdList: [],
  prizeNumberList: [],
  prizeProbabilityList: [],
  activityRmk: "",
});

const editNp = ref({});
const uploadCoverRef = ref();
const uploadLotteryRef = ref();
const prizeRules = ref([]);
const userLevelList = ref([]);
const userTypeList = ref([]);
const isVipList = ref([]);
const noUploadImg = ref(false);
const noUploadLotteryImg = ref(false);

const userGroups = ref([
  { label: "新用户", value: "0" },
  { label: "活跃用户", value: "1" },
  { label: "沉默用户", value: "2" },
  { label: "流失用户", value: "3" },
]);

const userTags = ref([
  { label: "高消费", value: "0" },
  { label: "低频消费", value: "1" },
  { label: "喜欢促销", value: "2" },
  { label: "品牌忠诚", value: "3" },
]);

const dialogVisible = ref(false);
const currentPrize = ref({});
const currentPrizeIndex = ref(-1);

// 选择全部用户时的改变事件
const handleUserTypeChange = (value) => {
  if (value === 1) {
    // 重置部分用户的选择条件
    form.value.userGarde = null;
    form.value.userIsVip = null;
    form.value.userGroup = [];
    form.value.userTags = [];
  }
};

// 列表左侧复选框
const handleSelectionChange = (row) => {
  form.value.ruleIdList = [];
  form.value.prizeNumberList = [];
  form.value.prizeProbabilityList = [];
  if (row && row.length > 0) {
    for (let i = 0; i < row.length; i++) {
      const element = row[i];
      form.value.ruleIdList.push(element.ruleId);
      form.value.prizeNumberList.push(element.prizeNumber);
      form.value.prizeProbabilityList.push(element.prizeProbability);
    }
  }
};

// 动态下拉框-获取字典值
const getDictList = () => {
  axios.get("/api/activity/getDictByType/" + "user_garde").then((res) => {
    if (res.data.code === 200) {
      userLevelList.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || "查询失败");
    }
  });
  axios.get("/api/activity/getDictByType/" + "joinUser").then((res) => {
    if (res.data.code === 200) {
      userTypeList.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || "查询失败");
    }
  });
  axios.get("/api/activity/getDictByType/" + "user_is_vip").then((res) => {
    if (res.data.code === 200) {
      isVipList.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || "查询失败");
    }
  });
};
getDictList();

// 获取规则列表
const getPrizeRules = () => {
  axios.post("/api/activity/getPrizeRules", editNp.value).then((res) => {
    if (res.data.code === 200) {
      prizeRules.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || "查询失败");
    }
  });
};
getPrizeRules();

// 添加活动
const addPrize = () => {
  form.value.activityRmk = quillEditorRef.value
    .getHTML()
    .replace(/<\/?p>/g, "");
  form.value.winner = form.value.winner ? 1 : 2;
  form.value.winnerRecord = form.value.winnerRecord ? 1 : 2;
  form.value.activityRules = form.value.activityRules ? 1 : 2;
  axios.post("/api/activity/addActivity", form.value).then((res) => {
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg || "添加成功");
      router.push("/list");
    } else {
      ElMessage.error(res.data.msg || "添加失败");
    }
  });
};

const editPrize = (index, row) => {
  // 清空上传组件的文件列表
  uploadCoverRef.value?.clearFiles();
  uploadLotteryRef.value?.clearFiles();
  currentPrizeIndex.value = index;
  currentPrize.value = cloneDeep(row); // 深克隆
  dialogVisible.value = true;
};

const savePrize = () => {
  let updForm = currentPrize.value;
  axios
    .put("/api/activity/updateRule", {
      ruleId: updForm.ruleId,
      ruleCover: updForm.ruleCover,
      ruleName: updForm.ruleName,
      rulePrize: updForm.rulePrize,
      ruleImage: updForm.ruleImage,
    })
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success("修改成功");
        editNp.value = {
          index: currentPrizeIndex.value,
          prizeNumber: updForm.prizeNumber,
          prizeProbability: updForm.prizeProbability,
        };
        getPrizeRules();
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.data.msg || "修改失败");
      }
    });
};

// 背景图片地址
const uploadBackgroundImg = (res) => {
  form.value.activityImage = res.data;
};

// 图片地址
const uploadImg = (res) => {
  currentPrize.value.ruleCover = res.data;
  noUploadImg.value = true;
};

// 中奖抽签图片地址
const uploadLotteryImg = (res) => {
  currentPrize.value.ruleImage = res.data;
  noUploadLotteryImg.value = true;
};

// 数量的改变事件
const prizeNumberChange = (prizeNumber) => {
  if (form.value.ruleIdList && form.value.ruleIdList.length > 0) {
    const currentRowIndex = form.value.ruleIdList.findIndex(
      (id) => id === currentPrize.value.ruleId
    );
    if (currentRowIndex !== -1) {
      form.value.prizeNumberList[currentRowIndex] = prizeNumber;
    }
  }
};

// 概率的改变事件
const prizeProbabilityChange = (prizeProbability) => {
  if (form.value.ruleIdList && form.value.ruleIdList.length > 0) {
    const currentRowIndex = form.value.ruleIdList.findIndex(
      (id) => id === currentPrize.value.ruleId
    );
    if (currentRowIndex !== -1) {
      form.value.prizeProbabilityList[currentRowIndex] = prizeProbability;
    }
  }
};
</script>

<style scoped>
.activity-form {
  max-width: 880px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input,
.el-date-editor {
  width: 100%;
}

.user-conditions {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.condition-hint {
  margin-top: 15px;
  padding: 10px;
  background-color: #e6f7ff;
  border-radius: 4px;
  color: #666;
  font-size: 14px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
</style>
